package com.carl.aop;

import com.carl.enums.DataSources;
import com.carl.utils.DataSourceSwitch;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class DataSourceAspect {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    private List<String> demoMethodList = Arrays.asList("find", "findAll");

    private DataSources data_source = DataSources.DEMO;

    private boolean packageFlag = false ;


    @Before("execution(* com.carl.dao..*.*(..))")
    public void before(JoinPoint point){
        if (packageFlag == false) {
            String thisMethodName = point.getSignature().getName();
            for (String methodName : demoMethodList) {
                if (thisMethodName.startsWith(methodName) == true) {
                    logger.info("## TEST-mybatis-test ---> DEMO--mybatis-demo##  ");
                    DataSourceSwitch.setDataSource(data_source);
                }
            }
        }
    }

    @Before("execution(* com.carl.demo.dao.*.*(..))")
    public void beforeDemo(JoinPoint point){
        System.out.println("  location : " + point.getSourceLocation());
        DataSourceSwitch.setDataSource(DataSources.DEMO);
        logger.info(" ### mybatis-demo dao @@");
        packageFlag = true ;
    }

    @After("execution(* com.carl.dao..*.*(..))")
    public void after(){
        if (packageFlag == false) {
            DataSourceSwitch.resetDataSource();
        }
    }

    @After("execution(* com.carl.demo.dao.*.*(..))")
    public void afterDemo(){
        DataSourceSwitch.resetDataSource();
    }

}
